//
//  MqForumChoiceViewController.m
//  Meiqi
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "MqForumChoiceViewController.h"
#import "MqForumModel.h"
#import "MqForumChoiceDetailViewController.h"
#import <MJRefresh.h>
#import "MqForumTableViewCell.h"
#import "MqForumModuleViewController.h"
#import <MBProgressHUD.h>
#define kForumChoiceAPI @"http://bbs.biketo.com/api/mobile/index.php?forum=digest&module=new_thread&page=1&version=4"

@interface MqForumChoiceViewController ()
<UITableViewDataSource, UITableViewDelegate>

//  菊花
@property (nonatomic, strong) MBProgressHUD *progressHUD;
//  请求的数据model数组
@property (nonatomic, strong) NSMutableArray *dataArray;

//  网络请求的地方
@property (nonatomic, assign) NSInteger startPage;

@property (nonatomic, strong) NSString *forum;

@property (nonatomic, strong) NSMutableArray *imgsArray;

//  数据库
//@property (nonatomic, strong) FMDatabase *db;

@end

@implementation MqForumChoiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    //  初始化数据源数组
    _dataArray = [NSMutableArray array];
    
    _imgsArray = [NSMutableArray array];
    
    
    //  初始化第一次获取的开始位置
    _startPage = 1;
    
    //  首界面数据默认展示
    _forum = @"digest";
//    NSString *name = [_forum stringByAppendingString:@".sqlite"];
    
    //  建表
    [[MqDatabase dataBaseHandle] buildListWithString:@"CREATE TABLE IF NOT EXISTS digest (tid text, author text, forumname text, subject text, coverpath text)"];
    
    NSString *selectString = [NSString stringWithFormat:@"SELECT *FROM %@", _forum];
    FMResultSet *result = [[MqDatabase dataBaseHandle].db executeQuery:selectString];
    
    while ([result next]) {
        
        //  取出数据库中每一行字段的值
        NSString *tid = [result stringForColumn:@"tid"];
        NSString *author = [result stringForColumn:@"author"];
        NSString *forumname = [result stringForColumn:@"forumname"];
        NSString *subject = [result stringForColumn:@"subject"];
        
        //  给model赋值
        MqForumModel *model = [[MqForumModel alloc] init];
        model.tid = tid;
        model.author = author;
        model.forumname = forumname;
        model.subject = subject;
        
        //  把model添加数组
        [_dataArray addObject:model];
        
    }

    /**
     *  循环创建button,并设置通用属性
     *  button的标题字体,正常状态颜色,选中颜色,tag值
     */
    for (int i = 0; i < 6; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = 100 + i;
        button.frame = CGRectMake(0 + kScreenWidth / 6 * i, 10, kScreenWidth / 6, 15);
        [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [button setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
        [button setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
        [self.view addSubview:button];
        
    }
    
    //  根据tag值关联button
    _recommendButton = [self.view viewWithTag:100];
    [_recommendButton setTitle:@"推荐" forState:(UIControlStateNormal)];
    _recommendButton.selected = YES;
    [_recommendButton addTarget:self action:@selector(changeView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    _travleButton = [self.view viewWithTag:101];
    [_travleButton setTitle:@"旅行" forState:(UIControlStateNormal)];
    [_travleButton addTarget:self action:@selector(changeView:) forControlEvents:(UIControlEventTouchUpInside)];

    
    _equipButton = [self.view viewWithTag:102];
    [_equipButton setTitle:@"装备" forState:(UIControlStateNormal)];
    [_equipButton addTarget:self action:@selector(changeView:) forControlEvents:(UIControlEventTouchUpInside)];

    _activityButton = [self.view viewWithTag:103];
    [_activityButton setTitle:@"活动" forState:(UIControlStateNormal)];
    [_activityButton addTarget:self action:@selector(changeView:) forControlEvents:(UIControlEventTouchUpInside)];

    
    _tattleButton = [self.view viewWithTag:104];
    [_tattleButton setTitle:@"杂谈" forState:(UIControlStateNormal)];
    [_tattleButton addTarget:self action:@selector(changeView:) forControlEvents:(UIControlEventTouchUpInside)];

    _menuButton = [self.view viewWithTag:105];
    _menuButton.frame = CGRectMake(kScreenWidth - 40, _tattleButton.top, 20, 15);
    [_menuButton addTarget:self action:@selector(pushToModule:) forControlEvents:(UIControlEventTouchUpInside)];
    [_menuButton setBackgroundImage:[UIImage imageNamed:@"forum_btn_more@2x"] forState:(UIControlStateNormal)];
    
    
    [self dataProcess];
    [self addTableView];
    [self setupProgressHud];
    
    //  tableView下拉刷新
//    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//       
//        _startPage = 1;
//        [self dataProcess];
//        
//    }];
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataProcess)];
    
//    NSMutableArray *array = [NSMutableArray array];
//    for (int i = 1; i < 10; i++) {
//        
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d", i]];
//        [array addObject:image];
//        
//    }
    
//    [header setImages:array forState:(MJRefreshStateRefreshing)];

    self.tableView.mj_header = header;
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];

    
    //  tableView上拉刷新
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
       
        _startPage = _startPage + 1;
        [self dataProcess];
        
    }];
}


//  版块按钮
- (void)pushToModule:(UIButton *)button{
    
    MqForumModuleViewController *moduleVC = [[MqForumModuleViewController alloc] init];
    
    [self.navigationController pushViewController:moduleVC animated:YES];
    
}

//  button的点击方法
- (void)changeView:(UIButton *)button{
    
    for (int i = 100; i < 105; i++) {
        
        if (i == button.tag) {
            
            button.selected = YES;
            
        }else{
            
            UIButton *button = [self.view viewWithTag:i];
            button.selected = NO;
        }
        
    }
    
    switch (button.tag) {
        case 100:
            _forum = @"digest";
            break;
            
        default:
            break;
            
        case 101:
            _forum = @"travel";
            break;
        
        case 102:
            _forum = @"equip";
            break;
            
        case 103:
            _forum = @"activity";
            break;
            
        case 104:
            _forum = @"talk";
            break;
    }
    
    [_tableView.mj_header beginRefreshing];
    
    
    //  数据库
//    [[MqDatabase dataBaseHandle] buildListWithString:name];
    
    NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (tid text, author text, forumname text, subject text, coverpath text)", _forum];
    
//    NSLog(@"%@",sql);
    
    
    //  使用sqlite语句建表
    [[MqDatabase dataBaseHandle].db executeUpdate:sql];
    
    
    //  从数据库取出数据赋值给dataArray
    //  执行查找的操作, 调用的方法是executeQuery,参数是sql的查找语句,会返回一个FMResultSet类型的结果

    NSString *selectString = [NSString stringWithFormat:@"SELECT *FROM %@", _forum];
    FMResultSet *result = [[MqDatabase dataBaseHandle].db executeQuery:selectString];
    
    while ([result next]) {
        
        //  取出数据库中每一行字段的值
        NSString *tid = [result stringForColumn:@"tid"];
        NSString *author = [result stringForColumn:@"author"];
        NSString *forumname = [result stringForColumn:@"forumname"];
        NSString *subject = [result stringForColumn:@"subject"];
        
        //  给model赋值
        MqForumModel *model = [[MqForumModel alloc] init];
        model.tid = tid;
        model.author = author;
        model.forumname = forumname;
        model.subject = subject;
        
        //  把model添加数组
        [_dataArray addObject:model];
        
    }
    
}

- (void)setupProgressHud{
    
    _progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
    _progressHUD.frame = self.view.bounds;
    _progressHUD.minSize = CGSizeMake(80, 80);
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_progressHUD];
    [_progressHUD show:YES];
    
}

//  添加tableView
- (void)addTableView{
    
    //  关闭scroll的自动布局
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 25, kScreenWidth, kScreenHeight - _recommendButton.bottom - 49 - 64) style:(UITableViewStylePlain)];
    
    //  设置tableView代理
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.rowHeight = 140;
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[MqForumTableViewCell class] forCellReuseIdentifier:@"MqForumTableViewCell"];
    
}

//  网络请求数据处理
- (void)dataProcess{
    /**
     *  ?forum=digest&module=new_thread&page=1&version=4
     */
   
    [PKRequestManager requestWithUrlString:[NSString stringWithFormat:@"http://bbs.biketo.com/api/mobile/index.php?forum=%@&module=new_thread&page=%ld&version=4", _forum,(long)_startPage] parDic:nil Method:GET finish:^(NSData *data) {
        
        [_progressHUD hide:YES];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        

        //  删除操作
        [[MqDatabase dataBaseHandle].db executeUpdate:[NSString stringWithFormat:@"DELETE FROM %@", _forum]];
        
        if (dic != nil) {
            
            if (_startPage == 1) {
                
                [_dataArray removeAllObjects];
                
            }
            
        }
        
        // NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (tid text, author text, forumname text, subject text, imgurl text)", _forum];
        NSArray *array = dic[@"Variables"][@"data"];
        
        for (NSDictionary *oneDic in array) {
            
            //  KVC赋值
            MqForumModel *model = [[MqForumModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            
            NSString *insertString = [NSString stringWithFormat:@"INSERT INTO %@ (tid, author, forumname, subject, coverpath) VALUES(?, ?, ?, ?, ?)", _forum];
            
            [[MqDatabase dataBaseHandle].db executeUpdate:[NSString stringWithFormat:@"%@", insertString],  model.tid, model.author, model.forumname, model.subject, model.coverpath];
            
            [_dataArray addObject:model];
            
        }
        
        //  刷新完成后关闭刷新动作
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        
        [_tableView reloadData];
        
    } error:^(NSError *error) {
        
        //  网络请求失败
        
    } path:nil];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
    
}

//  返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MqForumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MqForumTableViewCell" forIndexPath:indexPath];
    
    MqForumModel *model = _dataArray[indexPath.row];
    
    cell.model = model;
    
    return cell;
    
}

//  cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MqForumChoiceDetailViewController *detailVC = [[MqForumChoiceDetailViewController alloc] init];
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
    detailVC.forumModel = _dataArray[indexPath.row];
    
}

//  视图已经出现时
- (void)viewDidAppear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
